package com.xxxy.ljh.myapplication;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.android.material.textfield.TextInputEditText;
import com.xxxy.ljh.myapplication.Dao.ClubDao;
import com.xxxy.ljh.myapplication.DaoImpl.ClubDaoImpl;
import com.xxxy.ljh.myapplication.Manager.UserManager;
import com.xxxy.ljh.myapplication.R;
import com.xxxy.ljh.myapplication.dphelper.sqliteDBHelper;
import com.xxxy.ljh.myapplication.model.Club;
import com.xxxy.ljh.myapplication.model.User;

public class CreateClubActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1;
    private ImageView ivClubLogo;
    private TextInputEditText etClubName, etClubDescription, etClubPhone, etClubEmail;
    private Button btnClubCreate;
    private Uri selectedImageUri;
    private boolean isImageSelected = false;
    private ClubDao clubDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_create_club);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        initViews();
        setupListeners();
        setupClubNameValidation();
        clubDao = new ClubDaoImpl(this);
    }

    private void initViews() {
        ivClubLogo = findViewById(R.id.ivClubLogo);
        etClubName = findViewById(R.id.etClubName);
        etClubDescription = findViewById(R.id.etClubDescription);
        etClubPhone = findViewById(R.id.etClubPhone);
        etClubEmail = findViewById(R.id.etClubEmail);
        btnClubCreate = findViewById(R.id.btnClubCreate);
    }

    private void setupListeners() {
        ivClubLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openImagePicker();
            }
        });

        btnClubCreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleCreateClub();
            }
        });
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            selectedImageUri = data.getData();
            ivClubLogo.setImageURI(selectedImageUri);
            isImageSelected = true;
        }
    }

    private void handleCreateClub() {
        String clubName = etClubName.getText().toString().trim();
        String clubDescription = etClubDescription.getText().toString().trim();
        String clubPhone = etClubPhone.getText().toString().trim();
        String clubEmail = etClubEmail.getText().toString().trim();

        if (clubName.isEmpty() || clubDescription.isEmpty() || clubPhone.isEmpty() || clubEmail.isEmpty()) {
            Toast.makeText(this, "请填写所有信息", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!clubEmail.contains("@")) {
            Toast.makeText(this, "邮箱格式错误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!clubPhone.matches("^1[3-9]\\d{9}$")) {
            Toast.makeText(this, "手机号格式错误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!isImageSelected) {
            Toast.makeText(this, "请上传社团Logo", Toast.LENGTH_SHORT).show();
            return;
        }
        ClubDao clubDao = new ClubDaoImpl(this);
        if (((ClubDaoImpl) clubDao).isClubNameExists(clubName)) {
            etClubName.setError("社团名称已存在，请更换其他名称");
            etClubName.requestFocus();
            return;
        }

        // 创建社团逻辑
        createClub(clubName, clubDescription, clubPhone, clubEmail);
    }

    private void createClub(String name, String description, String phone, String email) {
        // 获取当前登录用户信息
        UserManager userManager = UserManager.getInstance(this);
        User currentUser = userManager.getCurrentUser();

        if (currentUser == null) {
            Toast.makeText(this, "用户信息异常，请重新登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 创建社团对象
        Club club = new Club(); // 使用正确的类名
        club.setAssociation_name(name);
        club.setDescription(description);
        club.setContact_phone(phone);
        club.setContact_email(email);
        club.setFounderId(currentUser.getUserId()); // 自动设置创建者ID为当前用户ID
        club.setAudit_status(0); // 设置为待审核状态
        club.setStatus(1); // 设置为有效状态
        club.setMemberCount(1); // 创建者自动成为第一个成员

        // 如果需要保存图片路径，可以转换URI为字符串
        if (selectedImageUri != null) {
            club.setLogo(selectedImageUri.toString()); // 保存图片URI
        }

        // 调用DAO创建社团
        boolean success = clubDao.createClub(club);

        if (success) {
            // 获取创建的社团ID
            int clubId = getClubIdByName(name);
            
            // 保存社团ID到SharedPreferences，以便社长审核成员申请
            SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
            prefs.edit().putInt("managed_club_id", clubId).apply();
            
            // 自动将创建者加入社团
            addFounderToClub(clubId, currentUser.getUserId());
            
            Toast.makeText(this, "申请社团创建成功", Toast.LENGTH_SHORT).show();
            finish(); // 返回上一个页面
        } else {
            Toast.makeText(this, "申请社团创建失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 根据社团名称获取社团ID
     * @param clubName 社团名称
     * @return 社团ID
     */
    private int getClubIdByName(String clubName) {
        // 获取当前登录用户信息
        UserManager userManager = UserManager.getInstance(this);
        User currentUser = userManager.getCurrentUser();

        if (currentUser == null) {
            return -1;
        }

        sqliteDBHelper dbHelper = new sqliteDBHelper(this);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] projection = {"association_id"};
        String selection = "association_name = ? AND founder_id = ?";
        String[] selectionArgs = {clubName, String.valueOf(currentUser.getUserId())};
        
        try {
            android.database.Cursor cursor = db.query(
                    "association",    // 表名
                    projection,       // 要查询的列
                    selection,        // WHERE子句
                    selectionArgs,    // WHERE子句参数
                    null,             // GROUP BY
                    null,             // HAVING
                    null              // ORDER BY
            );

            if (cursor != null && cursor.moveToFirst()) {
                int clubId = cursor.getInt(cursor.getColumnIndexOrThrow("association_id"));
                cursor.close();
                return clubId;
            }
            
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.close();
        }
        
        return -1; // 未找到对应社团
    }

    /**
     * 将创建者自动加入社团
     * @param clubId 社团ID
     * @param userId 用户ID
     */
    private void addFounderToClub(int clubId, int userId) {
        // 实现将创建者加入社团的逻辑
        // 这里应该向association_member表中插入一条记录
        // 状态设置为1（已通过），角色设置为社长（如2）
        sqliteDBHelper dbHelper = new sqliteDBHelper(this);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        
        try {
            ContentValues values = new ContentValues();
            values.put("association_id", clubId);
            values.put("user_id", userId);
            values.put("member_role", 2); // 社长角色
            values.put("status", 1); // 已通过
            values.put("apply_time", System.currentTimeMillis());
            values.put("approve_time", System.currentTimeMillis());
            values.put("approver_id", userId); // 自己批准自己
            values.put("approve_remark", "社团创建者自动加入");
            
            long result = db.insert("association_member", null, values);
            if (result == -1) {
                Toast.makeText(this, "创建者加入社团失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "创建者加入社团时发生错误", Toast.LENGTH_SHORT).show();
        } finally {
            db.close();
        }
    }

    private void setupClubNameValidation() {
        etClubName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ClubDao clubDao = new ClubDaoImpl(CreateClubActivity.this);
                if (((ClubDaoImpl) clubDao).isClubNameExists(s.toString().trim()) && s.length() > 0) {
                    etClubName.setError("社团名称已存在");
                } else {
                    etClubName.setError(null);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });
    }
}